﻿(function ($) {
    $.fn.extend({
        //pass the options variable to the function
        DynamicDropdownPlugin: function (options) {
            var defaults = {
                DropdownMode: "Content",
                MultiSelect: false,
                HeaderDefaultText: "",
                HeaderPreText: "",
                HeaderValueFieldId: "",
                Width: "200px",
                OnDropdownChanged: null,
                OnDropdownChanging: null
            }

            var options = $.extend(defaults, options);

            return this.each(function () {
                // VALIDATE SETUP PROPERTIES
                ValidateOptions(options);

                var dropdownSelector = '#' + $(this).attr("id");
                var innerHtml = $(dropdownSelector).html();
                $(dropdownSelector).addClass("dropDownFilter");

                // WRAP HTML
                $(dropdownSelector).html("<a href='#' class='trigger'><span id='HeaderText' class='padding'></span><span class='arrow'></span></a>" +
											"<div class='toggleContainer'>" +
												"<div class='animate' id='search'>" +
												innerHtml +
												"</div>" +
											"</div>");

                $(dropdownSelector).css("width", options.Width); //set width

                if (options.DropdownMode == "Content") { //add content class if it is such
                    $(dropdownSelector).addClass('content');
                }
                $(dropdownSelector + " #HeaderText").text(options.HeaderDefaultText);

                $(dropdownSelector).find(".button").addClass('actionButton');

                if (!options.MultiSelect) {
                    $(dropdownSelector).find(".button").addClass('trigger');
                }
                else {
                    $(dropdownSelector).find(".animate").append("<div class='closeButton'>close</div>");
                    $(dropdownSelector).find(".button").addClass('multiSelectBox');
                    $(dropdownSelector).find(".button").wrapInner("<span />");
                    $(dropdownSelector).find(".button").prepend("<img class='multiSelectImg' src='../images/cb_off.jpg' />");
                    preloadImg();
                }

                function preloadImg() {
                    var imgSwap = [];
                    $(dropdownSelector + " .multiSelectImg").each(function () {
                        imgUrl = this.src.replace("_off", "_on");
                        imgSwap.push(imgUrl);
                    });
                    $(imgSwap).preload();
                }

                // once we're done manipulating designated buttons remove the class
                $(dropdownSelector).find(".button").removeClass('button');

                // add the header text
                $(dropdownSelector + " #HeaderText").text(options.HeaderDefaultText);

                var itemIndex = null;
                // KEYUP EVENT
                //select inner div by dropdown selector, make sure it is not of type content
                $(dropdownSelector).keyup(function (event) {
                    if (event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 13) return;

                    var ListItem = $(dropdownSelector + ":not('.content')");
                    if (ListItem.length == 0) return;

                    var selectedItem = $(this).children(".toggleContainer:visible").find(".animate .actionButton");
                    if (selectedItem.length == 0) return;

                    if (event != null && event.keyCode == 40) { // downkey
                        if (itemIndex == null) {
                            itemIndex = 0;
                        }
                        else if ((itemIndex + 1) < $(selectedItem).length) {
                            itemIndex++;
                        }
                        else {
                            itemIndex = 0;
                        }
                        $(selectedItem).removeClass("active");
                        $(selectedItem[itemIndex]).addClass("active");
                        if (!options.MultiSelect) UpdateDropDown($(selectedItem[itemIndex]));
                    }
                    else if (event != null && event.keyCode == 38) { // upkey
                        if (itemIndex == 0 || itemIndex == null) {
                            itemIndex = $(selectedItem).length - 1;
                        }
                        else itemIndex--;

                        $(selectedItem).removeClass("active");
                        $(selectedItem[itemIndex]).addClass("active");
                        if (!options.MultiSelect) UpdateDropDown($(selectedItem[itemIndex]));
                    }
                    else if (event != null && event.keyCode == 13) { // enter
                        if (options.MultiSelect) {
                            toggleMulti(selectedItem[itemIndex]);
                            $(selectedItem[itemIndex]).removeClass("active");
                        }
                        UpdateDropDown($(selectedItem[itemIndex]));
                    }
                });


                // CLICK EVENT
                $(dropdownSelector + ' .actionButton').click(function (e) {
                    e.preventDefault();
                    if (options.MultiSelect) {
                        e.stopPropagation();
                        toggleMulti(this);
                    }
                    UpdateDropDown(this)
                });

                function toggleMulti(item) {
                    if ($(item).hasClass("activeMulti")) {
                        $(item).removeClass("activeMulti");
                        $(item).find(".multiSelectImg").attr("src", "../images/cb_off.jpg");
                    }
                    else {
                        $(item).addClass("activeMulti");
                        $(item).find(".multiSelectImg").attr("src", "../images/cb_on.jpg");
                    }
                }

                // BASIC UPDATE FUNCTION
                function UpdateDropDown(dditem) {
                    var item = '';
                    if (options.DropdownMode == "Content") { //add content class if it is such
                        item = $("#" + options.HeaderValueFieldId);
                    }
                    else if (options.DropdownMode == "Select") {
                        item = $(dditem);
                    }

                    if (options.OnDropdownChanging != null) {
                        options.OnDropdownChanging(item);
                    }

                    setHeaderText(item);

                    if (options.OnDropdownChanged != null) {
                        options.OnDropdownChanged(item);
                    }
                }

                // ADVANCED UPDATE FUNCTION
                $(dropdownSelector).bind('updateText', function (event, text) {
                    $(dropdownSelector + ' #HeaderText').text(options.HeaderPreText + text);
                    $(dropdownSelector).click();
                });


                // Controls updates to text at the top of the dropdown
                var itemArray = new Array();
                function setHeaderText(valueItem, input) {
                    var updateText = '';
                    if (valueItem != null && valueItem != '') {
                        //multiselect dropdown text
                        if (options.MultiSelect) {
                            var itemText = $(valueItem).text();
                            if ($.inArray(itemText, itemArray) == -1) {
                                itemArray.push(itemText);
                            }
                            else {
                                for (var i = 0; i < itemArray.length; i++) {
                                    if (itemArray[i] == itemText) {
                                        itemArray.splice(i, 1);
                                    }
                                }
                            }
                            if (itemArray.length > 0) {
                                for (var i = 0; i < itemArray.length; i++) {
                                    updateText += itemArray[i] + ", ";
                                }
                                updateText = options.HeaderPreText + updateText.substring(0, updateText.length - 2);
                            }
                            else updateText = options.HeaderDefaultText;
                        }
                        // else simply update the dropdown with one item
                        else {
                            if ($(valueItem).text() != null && $(valueItem).text() != "") {
                                updateText = options.HeaderPreText + $(valueItem).text();
                            }
                            else if ($(valueItem).val() != '') {
                                updateText = options.HeaderPreText + $(valueItem).val();
                            }
                            else {
                                updateText = options.HeaderDefaultText;
                            }
                        }

                        $(dropdownSelector + ' #HeaderText').text(updateText);
                        if (input) $(input).val(vals);

                        // Adjust height accordingly
                        if (options.MultiSelect) $(dropdownSelector + ' .toggleContainer').css({
                            'top': $(dropdownSelector).height()
                        });
                    }
                }

            }); // END EACH

            function ValidateOptions(options) {
                if (options.HeaderDefaultText == "") {
                    alert("HeaderDefaultText must be initialized in the DynamicDropdownPlugin: " + $(this).attr("id"));
                }
                if (options.HeaderValueFieldId == "" && options.DropdownMode == "Content") {
                    alert("HeaderValueFieldId must be initialized in the DynamicDropdownPlugin: " + $(this).attr("id"));
                }
            }

        } //end DynamicDropdownPlugin function

    });
    $.fn.preload = function () {
        this.each(function () {
            $('<img/>')[0].src = this;
        });
    }

})(jQuery);


/* THIS CODE APPLIES TO ALL DROPDOWNS AND THUS DOES NOT NEED TO RESIDE IN THE PLUGIN SECTION */

$(document).ready(function () {
    // CREATE CURSOR ON HOVER FOR ALL DROPDOWNS
    $('.dropDownFilter').hover(function () {
        $(this).css('cursor', 'pointer');
    });

    //  PREVENT SCROLL FOR OPEN DROPDOWNS
    $(document).keydown(function (event) {
        if ((event.keyCode == 40 || event.keyCode == 38) && $(".toggleContainer:visible").length > 0) {
            event.preventDefault();
        }
    });

    // DONT CLOSE FOR CONTENT DROPDOWNS
    $(".toggleContainer").click(function (e) {
        if ($(this).parent().hasClass('content')) {
            e.preventDefault();
            e.stopPropagation();
        }
    });

    $('body').click(function (e) {
        $(".toggleContainer:visible").slideUp(function () {
            setCorners();
        });
    });

    $(".closeButton").click(function (e) {
        $(this).parent().parent().parent().click();
    });

    InitDropDowns();
});

function setCorners() {
    $(".dropDownFilter").css({
        'border-radius': '10px',
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px'
    });
}

function InitDropDowns() {
    var $dropDown = $('.dropDownFilter');
    var $toggleContainerBase = $dropDown.find('.toggleContainer');
    if ($dropDown.length == 0) {
        throw "No dropdowns were found. Please ensure that the plugin script is attached after the script that calls the plugin.";
    }
    $dropDown.each(function () {
        var $this = $(this);
        var $thisHeight = $this.height();
        var $thisWidth = $this.width();
        var $toggleContainer = $this.find('.toggleContainer');

        // set toggleContainers posistion and width

        $('.toggleContainer', this).css({
            'top': $thisHeight,
            'left': '-1px'
            //'width': $thisWidth
        })


        $toggleContainerBase.find('.animate').stop().animate({
            'opacity': '0'
        }); // end animate opaicty to zero

        // trigger event
        $('.trigger', this).click(function () {

            // set animate opacity to zero
            $toggleContainerBase.find('.animate').stop().animate({
                'opacity': '0'
            }); // end animate opaicty to zero

            // slide all open containers up
            if ($toggleContainerBase.is(':visible')) {
                $toggleContainerBase.slideUp('fast', function () {
                    // reset rounded corners
                    $(this).parent().css({
                        'border-radius': '10px',
                        '-webkit-border-radius': '10px',
                        '-moz-border-radius': '10px'
                    }); // end reset rounded corners
                }); // end slide all open containers
            }

            // remove rounded corners from bottom
            $this.css({
                'border-radius': '10px 10px 0 0',
                '-webkit-border-radius': '10px 10px 0 0',
                '-moz-border-radius': '10px 10px 0 0'
            }); // end rounded corners from bottom

            // remove active class
            //$dropDown.find('.trigger').removeClass('active');

            // if toggleContainer is hidden
            if ($toggleContainer.is(':hidden')) {
                $thisHeight = $this.height();
                $thisWidth = $this.width();
                $('.toggleContainer').css({
                    'top': $thisHeight,
                    'left': '-1px'
                    //'width': $thisWidth
                });

                // slide down
                $toggleContainer.slideDown(200); // end slideToggle
                $toggleContainer.find('.animate').stop().animate({
                    'opacity': '1'
                }, 600, function () {
                    // select the value of input field w/ class of .focusMe
                    $(this).find('.focusMe').select();
                    $(this).find('.focusMe').click(function () {
                        $(this).select();
                    });
                }); // end animate opaicty to zero

                // add active class to trigger
                //$this.find('.trigger').addClass('active');
            }; // end if

            return false;
        }); // end click event
    });   // end $dropDown.each
}
